package com.tcl.logoidentify.commons;

import java.util.Iterator;
import java.util.NoSuchElementException;

public class CircleQueue implements Iterable<byte[]> {

	private volatile byte[][] data = null;
	private int index = -1;

	public CircleQueue(int size, int msgSize) {
		data = new byte[size][msgSize];
	}

	public synchronized void add(byte[] e) {
		if (++index < size())
			data[index] = e;
		else {
			index = index % size();
			data[index] = e;
		}
	}

	public int size() {
		return data.length;
	}

	@Override
	public String toString() {

		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < data.length; i++) {
			sb.append(new String(data[i])).append(",");
			if (i >= 20) {
				sb.append(",,后边还有");
				break;
			}
		}
		return sb.toString();
	}

	@Override
	public Iterator<byte[]> iterator() {
		return new QueueIterator(index, data);
	}

	private static class QueueIterator implements Iterator<byte[]> {
		int num = 0;
		int index = -1;
		private byte[][] data = null;

		public QueueIterator(int index, byte[][] data) {
			this.index = index;
			this.data = data;
		}

		@Override
		public boolean hasNext() {
			return num < data.length;
		}

		@Override
		public byte[] next() {
			if (!hasNext())
				throw new NoSuchElementException();
			num++;
			if (index < 0) {
				index = data.length + index;
				return data[index--];
			} else {
				return data[index--];
			}
		}

		@Override
		public void remove() {
			throw new UnsupportedOperationException();
		}
	}
}
